<template>
  <div class="app-container">
    <!-- 左侧角色列表 -->
    <div class="left">
      <div class="role-grid">
        <div v-for="role in roleData" :key="role.id" class="role-item" :class="{ 'selected': selectedRole === role.id }"
          @click="selectRole(role.id)">
          {{ role.name }}
        </div>
      </div>
    </div>

    <!-- 右侧功能权限设置 -->
    <div class="right">
      <div class="right-buttone">
        <el-row type="flex" justify="end">
          <el-button size="mini" type="primary" @click="savePermissionsDebounced">保存</el-button>
          <el-button size="mini" @click="defaultRolePowerDebounced">恢复默认</el-button>
        </el-row>
      </div>
      <div class="right-content">
        <div v-for="(permissions, categoryType) in categorizedPermissions" :key="categoryType">
          <div class="power-item">
            <div class="power-h3">
              <!-- 全选复选框 -->
              <el-checkbox :indeterminate="isIndeterminate(categoryType)" v-model="isAllSelected[categoryType]"
                @change="handleAllSelect(categoryType)" size="mini"
                :disabled="selectedRole === 1 && disabledCategories.has(categoryType)">
              </el-checkbox>
              {{ getCategoryName(categoryType) }}
            </div>
            <!-- 功能权限标题 -->
            <div class="power-h4">功能权限</div>
            <!-- 权限复选框组 -->

            <el-checkbox-group v-model="selectedPermissions[categoryType]" class="checkbox-container">
              <el-checkbox v-for="permission in permissions" :key="permission.ID" :label="permission.ID"
                @change="handlePermissionChange(permission)" :disabled="permission.disabled" class="checkbox-item">
                {{ permission.power_name }}
              </el-checkbox>
            </el-checkbox-group>


          </div>

        </div>

      </div>



    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getRolePower, updateRolePower, defaultRolePower } from '@/api/power';
import { debounce } from 'lodash';
export default {
  name: 'RoleSetting',
  computed: {
    ...mapGetters([
      'sysRole'
    ])
  },
  data() {
    return {
      selectedRole: 1,
      roleData: [
        { id: 1, name: '系统管理员', children: [] },
        { id: 2, name: '校长', children: [] },
        { id: 3, name: '财务', children: [] },
        { id: 4, name: '教务主任', children: [] },
        { id: 5, name: '教务', children: [] }
      ],
      permissions: [],
      selectedPermissions: {},
      categorizedPermissions: {},
      isAllSelected: {},
      disabledCategories: new Set(),
    };
  },
  created() {
    this.selectedRole = this.sysRole
    // this.categorizePermissions();
    this.getRolePower()
    // 初始化防抖函数
    this.savePermissionsDebounced = debounce(this.savePermissions, 1000); // 1秒防抖
    this.defaultRolePowerDebounced = debounce(this.defaultRolePower, 1000); // 1秒防抖
  },
  methods: {
    // 获取角色权限
    async getRolePower() {
      let result = await getRolePower({ fk_t_ep_role_id: this.selectedRole })
      this.permissions = result
      this.categorizePermissions()

    },
    // 组装后台权限区分分类
    categorizePermissions() {
      this.permissions.forEach(permission => {
        const categoryType = permission.category_type;
        // 初始化 categorizedPermissions
        if (!this.categorizedPermissions[categoryType]) {
          this.$set(this.categorizedPermissions, categoryType, []);
        }
        // 初始化 selectedPermissions
        if (!this.selectedPermissions[categoryType]) {
          this.$set(this.selectedPermissions, categoryType, []);
        }
        // 初始化 isAllSelected
        if (!this.isAllSelected[categoryType]) {
          this.$set(this.isAllSelected, categoryType, false);
        }
        // 强制设置 "系统设置" 按钮为选中状态，并且不可取消
        if (permission.power_code === '099001' && this.selectedRole == 1) { // 假设权限名称为 "系统设置"
          permission.is_own = 1; // 强制选中
          permission.disabled = true; // 标记为不可操作
          this.disabledCategories.add(String(permission.category_type)); // 记录分类类型
        }
        // 将权限添加到对应的分类中
        this.categorizedPermissions[categoryType].push(permission);

        if (permission.is_own === 1) {
          this.selectedPermissions[categoryType].push(permission.ID);
        }
      });
      // 动态计算每个分类的全选状态
      for (const categoryType in this.categorizedPermissions) {
        const allPermissionIds = this.categorizedPermissions[categoryType]
          .filter(permission => !permission.disabled) // 排除禁用的权限
          .map(permission => permission.ID);

        const selected = this.selectedPermissions[categoryType];

        // 判断是否全选
        this.isAllSelected[categoryType] = selected.length > 0 && selected.length === allPermissionIds.length;
        // 如果分类被禁用，则强制设置全选框为勾选状态

        if (this.selectedRole === 1 && this.disabledCategories.has(categoryType)) {
          this.isAllSelected[categoryType] = true;
        }
      }

    },
    // 获取分类权限名称
    getCategoryName(categoryType) {
      switch (categoryType.toString()) {
        case "1":
          return '组织管理权限';
        case "2":
          return '客户管理权限';
        default:
          return '未知权限';
      }
    },
    // 改变权限可见
    handlePermissionChange(permission) {
      if (permission.disabled) {
        return;
      }
      const categoryType = permission.category_type;
      // 切换 is_own 的值（0 或 1）
      permission.is_own = permission.is_own === 1 ? 0 : 1;

      // 同步更新 selectedPermissions
      const index = this.selectedPermissions[categoryType].indexOf(permission.ID);
      if (permission.is_own === 1 && index === -1) {
        this.selectedPermissions[categoryType].push(permission.ID);
      } else if (permission.is_own === 0 && index !== -1) {
        this.selectedPermissions[categoryType].splice(index, 1);
      }
      const allPermissionIds = this.categorizedPermissions[categoryType].map(p => p.ID);
      const selected = this.selectedPermissions[categoryType];

      this.isAllSelected[categoryType] = selected.length === allPermissionIds.length;
    },
    // 全选操作
    handleAllSelect(categoryType) {
      if (this.disabledCategories && this.disabledCategories.has(categoryType)) {
        return;
      }
      const allPermissionIds = this.categorizedPermissions[categoryType].filter(permission => !permission.disabled).map(p => p.ID);
      const newValue = this.isAllSelected[categoryType] ? 0 : 1;

      // 更新所有权限的 is_own 值
      this.categorizedPermissions[categoryType].forEach(permission => {
        if (!permission.disabled) {
          permission.is_own = newValue;
        }
      });

      // 更新 selectedPermissions
      this.selectedPermissions[categoryType] = newValue === 1 ? [...allPermissionIds] : [];

      // 更新全选状态
      this.isAllSelected[categoryType] = newValue === 1;
    },
    // 判断是否全选
    isIndeterminate(categoryType) {
      const selected = this.selectedPermissions[categoryType];
      const allPermissionIds = this.categorizedPermissions[categoryType].filter(permission => !permission.disabled).map(p => p.ID);
      return selected.length > 0 && selected.length < allPermissionIds.length;

    },
    // 切换角色
    selectRole(id) {
      this.selectedRole = id
      this.categorizedPermissions = {}
      this.selectedPermissions = {}
      this.isAllSelected = {}
      this.permissions = []
      this.getRolePower()
    },
    // 保存
    async savePermissions() {
      try {
        await updateRolePower({ rolePowerList: this.permissions });
        this.$message.success(`保存成功`);
      } catch (error) {
        this.$message.error(`保存失败，请稍后重试`);
      }
    },
    // 重置
    async defaultRolePower() {
      try {
        await defaultRolePower({ fk_t_ep_role_id: this.selectedRole });

        this.$message.success(`重置成功`);
        this.categorizedPermissions = {};
        this.selectedPermissions = {};
        this.isAllSelected = {};
        this.permissions = [];
        this.getRolePower();
      } catch (error) {
        this.$message.error(`恢复默认失败，请稍后重试`);
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  display: flex;
  background-color: #fff;
}

.left {
  width: 280px;
  padding: 20px;
  border-right: 1px solid #eaeef4;
  overflow-y: auto;

  .role-grid {
    display: grid;
    /* 每行显示两个格子 */
    gap: 16px;
    /* 格子之间的间距 */
  }

  .role-item {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s, border-color 0.3s;
  }


  .role-item.selected {
    background-color: #d5ebe5;
    color: #3eb0bb;
  }

}

.right {
  flex: 1;
  padding-left: 20px;

  .right-buttone {
    margin-bottom: 20px;
  }

  .right-content {
    height: calc(80vh - 100px);
    /* 设置高度为视口高度减去顶部和底部的填充或者边框 */
    overflow-y: auto;
  }

  .power-item {
    border: 1px solid #ccc;
    margin-bottom: 20px;


    .power-h3 {
      padding-left: 10px;
      height: 40px;
      line-height: 40px;
      background-color: #f2f2f2;
    }

    .power-h4 {
      margin: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f2f2f2;
    }

    .checkbox-container {
      display: flex;
      flex-wrap: wrap;
      margin-left: 20px;
      margin-bottom: 20px;

    }

    /* 每个复选框的宽度 */
    .checkbox-item {

      width: calc(20% - 10px);
      /* 每个复选框占20%宽度，并减去间距 */
      margin-right: 5px;
      /* 右侧间距 */
      margin-bottom: 5px;
      /* 底部间距 */
    }

    .checkbox-item:last-child {
      margin-right: 0;
    }
  }

}
</style>